<template>
    <div class="point-ran">
        <Amap ref="amap" :lng="lng" :lat="lat" @complete="complete" @click="onClick" class="the-map"></Amap>

        <div v-if="operateType == OperateTypeEnum.ADDING || operateType == OperateTypeEnum.EDITING" class="draw-tip">
            <a-space v-if="operateType == OperateTypeEnum.EDITING" style="padding: 0 0 20px 0;">
                <a-button @click="confirmEdit" type="primary">确定</a-button>
                <a-button @click="deleteEdit" type="primary" danger>删除</a-button>
                <a-button @click="cancelEdit">取消</a-button>
            </a-space>
            <a-space v-else style="padding: 0 0 20px 0;">

                <a-button @click="cancelAdd">取消</a-button>
            </a-space>

            <div class="draw-tip-text"> {{ tipText }} </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import Amap from './Amap.vue';
import locationImg from '@/assets/map/location.png'
const props = withDefaults(defineProps<{
    isUpdatePoint?: boolean,
    isUpdateRange?: boolean
}>(), {
    isUpdatePoint: true,
    isUpdateRange: true
})

const lng = defineModel<number>('lng')
const lat = defineModel<number>('lat')
const range = defineModel<{ lng: number, lat: number }[]>('range', { default: [] })
const rangeCopy = ref<{ lng: number, lat: number }[]>()
const emit = defineEmits<{
    complete: [AMap.Map]
}>()

let map: AMap.Map;
const tipText = ref('鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制')
const amap = ref()
const initCount = ref(0)
let polyEditor: AMap.PolygonEditor
let mouseTool: AMap.MouseTool
let infoWindow: AMap.InfoWindow
enum OperateTypeEnum {
    NONE = 0,
    /**添加操作中 */
    ADDING = 1,
    /**修改操作中 */
    EDITING = 2,
    /**删除 */
    DELETE = 3,
    /**编辑 */
    SAVE = 4,
    /**取消 */
    CANCEL = 5
}

const operateType = ref<OperateTypeEnum>(OperateTypeEnum.NONE)

watch(() => lng.value, () => {
    initCount.value++
    if (lng.value && lat.value) {

        addPoint(lng.value, lat.value)
        if (initCount.value == 2) {
            map.panTo([lng.value, lat.value], 200)
        }
    }
})

watch(() => range.value, () => {
    if (range.value) {
        addRange(range.value)
    }
})

const complete = (e: AMap.Map) => {
    map = e
    initCount.value++
    if (lng.value && lat.value) {

        addPoint(lng.value, lat.value)
        if (initCount.value == 2) {
            map.panTo([lng.value, lat.value], 200)
        }

    }
    if (range.value) {
        addRange(range.value)
    }
    emit('complete', e)
}
const onClick = (e: any) => {
    if (!props.isUpdatePoint) {
        return
    }
    if (operateType.value != OperateTypeEnum.NONE) {
        return
    }

    console.log(e.lnglat)
    let lnglat: AMap.LngLat = e.lnglat

    addPoint(lnglat.lng, lnglat.lat)
    lng.value = lnglat.lng
    lat.value = lnglat.lat
}
const addPoint = (lng: number, lat: number) => {
    let myMarker = getMyMarker()
    if (myMarker) {
        map.remove(myMarker)
    }
    let textList = map.getAllOverlays('text')
    for(let text of textList){
        map.remove(text)
    }


    // let _url = "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"
    // let _width = 25
    // let _height = 34
    let _url = locationImg
    let _width = 46
    let _height = 62
    let icon = new AMap.Icon({
        size: new AMap.Size(_width, _height), // 图标尺寸
        image: _url,
        imageSize: new AMap.Size(_width, _height),
    });


    let marker = new AMap.Marker({
        icon: icon,
        position: [lng, lat],
        anchor: 'bottom-center',
        title: '点击我，可设置范围',
        extData: {
            isMy: true
        },
        map
    });


    marker.on('click', (e: any) => {
        handleMarkerClick(e)
    })

    var text = new AMap.Text({
        position: new AMap.LngLat(lng, lat),
        anchor: 'bottom-center',
        offset: new AMap.Pixel(0, -70),
        text: '点击我，可设置范围',
    });
    map.add(text);

    setTimeout(() => {
        map.remove(text)
    }, 2000)

    return marker
}

const addRange = (list: { lng: number, lat: number }[]) => {
    if (list.length == 0) {
        return
    }
    let myPoly = getMyPolygon()
    if (myPoly) {
        map.remove(myPoly)
    }


    let polygon = new AMap.Polygon();
    let path: [number, number][] = list.map((obj) => {
        return [obj.lng, obj.lat];
    });
    polygon.setOptions({
        path: path, //设置多边形边界路径
        strokeColor: '#FA5151', //线颜色
        strokeOpacity: 0.9, //线透明度
        strokeWeight: 1, //线宽
        fillColor: '#FA5151', //填充色
        fillOpacity: 0.5, //填充透明度
        zIndex: 10,
        bubble: true,
        extData: {
            isMy: true
        },

    })
    // polygon.on('click', (e: any) => {
    //     onClick(e)
    // })
    map.add(polygon)
}

const handleMarkerClick = (e: any) => {
    if (!props.isUpdateRange) {
        return
    }
    if (operateType.value != OperateTypeEnum.NONE) {
        return
    }

    let myPoly = getMyPolygon()
    if (myPoly) {
        tipText.value = '编辑完成后，点击保存按钮'
        rangeCopy.value = JSON.parse(JSON.stringify(range.value))
        operateType.value = OperateTypeEnum.EDITING

        polyEditor = new AMap.PolygonEditor(map, getMyPolygon());
        polyEditor.open();
        polyEditor.on('end', (e) => {
            let p: AMap.Polygon = e.target


            let path: AMap.LngLat[] = p.getPath() as AMap.LngLat[]
            let scope = path.map(lngLat => {
                return {
                    lat: lngLat.lat,
                    lng: lngLat.lng
                }
            })
            range.value = scope

            operateType.value = OperateTypeEnum.NONE
        })



    } else {
        tipText.value = '鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制'
        operateType.value = OperateTypeEnum.ADDING
        mouseTool = new AMap.MouseTool(map)
        mouseTool.polygon({
            fillColor: '#FA5151',
            strokeColor: '#FA5151',
            zIndex: 10,
            //同Polygon的Option设置
        });
        mouseTool.on('draw', (e) => {
            mouseTool.close(false)
            let obj: AMap.Polygon = e.obj
            obj.setOptions({
                bubble: true,
                extData: {
                    isMy: true
                },
            })
            // obj.on('click', (e: any) => {
            //     onClick(e)
            // })
            let path: AMap.LngLat[] = obj.getPath() as AMap.LngLat[]
            let scope = path.map(lngLat => {
                return {
                    lat: lngLat.lat,
                    lng: lngLat.lng
                }
            })
            range.value = scope

            operateType.value = OperateTypeEnum.NONE
            // infoWindow.close()
        })
    }
}

const getMyMarker = () => {
    let list = map.getAllOverlays('marker')
    for (let item of list) {
        let extData = item.getExtData()
        if (extData.isMy) {
            return item
        }
    }
    return null
}
const getMyPolygon = () => {
    let list = map.getAllOverlays('polygon')
    for (let item of list) {
        let extData = item.getExtData()
        if (extData.isMy) {
            return item
        }
    }
    return null
}

const confirmEdit = () => {
    operateType.value = OperateTypeEnum.NONE
    polyEditor.close()

}


const deleteEdit = () => {
    operateType.value = OperateTypeEnum.NONE
    polyEditor.close()

    map.remove(getMyPolygon())

    range.value = []

}


const cancelEdit = () => {
    operateType.value = OperateTypeEnum.NONE
    polyEditor.close()

    setTimeout(() => {
        //复原多边形

        let polyPath: [number, number][] = rangeCopy.value!.map((obj) => {
            return [obj.lng, obj.lat];
        });
        getMyPolygon().setPath(polyPath)
    }, 500)




}
const cancelAdd = () => {
    operateType.value = OperateTypeEnum.NONE
    mouseTool.close(true)
}


</script>
<style scoped>
.point-ran {
    position: relative;
}

.the-map {
    height: 100%;

}

@keyframes beat {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-moz-keyframes beat

/* Firefox */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-webkit-keyframes beat

/* Safari 和 Chrome */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-o-keyframes beat

/* Opera */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

.draw-tip {
    position: absolute;
    right: 5%;
    top: 10%;
    padding: 10px 20px;
    z-index: 10;
    background: #fff;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
}

.draw-tip-text {
    color: #e73d4a;
    animation: beat 1s infinite;
    -moz-animation: beat 1s infinite;
    /* Firefox */
    -webkit-animation: beat 1s infinite;
    /* Safari 和 Chrome */
    -o-animation: beat 1s infinite;
}

.tip-text {
    display: inline-block;
    padding: 0 40px 0 0;
}

.search-p {
    padding: 10px 20px;
    background: #fff;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 1);
    position: absolute;
    top: 20px;
    left: 20px;
}
</style>
